//
//  TLZoomBarViewController.m
//  FunnyVideo
//
//  Created by 李鑫 on 15/8/12.
//  Copyright (c) 2015年 NewEggTech. All rights reserved.
//


#define CellOffsetYFactor -0.05

#define INPUT_HEIGHT 40.0f

#import "TLZoomBarTableViewController.h"

#import "TLVideoCell.h"

#import "NSURL+Signature.h"

#import "MentionPullToReactView.h"

#import "PullToReact.h"

#import "UserLoginTBVCtrl.h"

#import "TLCommentManger.h"

#import "AVOSManger.h"
#import "TXYVideoThumbFetcher.h"

#import "UIView+AnimationOptionsForCurve.h"
#import "UIButton+JSMessagesView.h"

#import "TLLoginViewController.h"

#import "TLZoomBarTableViewController.h"

#import "FSDropDownMenu.h"

#import "NSIndexPath+Menu.h"

#import "TLCategoryManger.h"

#define INDICATORRADIUS 50.f

typedef enum : NSUInteger {
    TLRefreshControlStateRefresh,
    TLRefreshControlStateCategory,
    TLRefreshControlStateNone,
} TLRefreshControlState;

@interface TLZoomBarTableViewController () <VideoEventDelegate,JSDismissiveTextViewDelegate,UIViewControllerTransitioningDelegate,FSDropDownMenuDelegate>
{
    //是否正在上拉刷新
    BOOL scrolling;


    
    NSString *currentObjectId;
}

@property (nonatomic, weak) UIView *transitionCell;
@property (nonatomic, strong) TLVideoCell *currentVideoCell;
@property (nonatomic, strong) FSDropDownMenu *menu;
@property (nonatomic, assign) TLRefreshControlState state;
@property (nonatomic, assign) AVOSVideoType category;
@property (nonatomic, assign) BOOL isShowCmt;
//@property (nonatomic, assign) BOOL isloading;
//@property (nonatomic, assign)
@end

@implementation TLZoomBarTableViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    self.isShowCmt  = NO;
    isCategorySwOn = YES;
    //Load Defaults Video Type
    [self loadMoreVideoWithVideoType:[[AVOSManger sharedManger] videoType]];
    
    [self addPullLoadControl];
    
    
    
    self.title = Nav_Img_Logo;
    
    CGPoint point = CGPointMake(0, self.navigationController.navigationBar.frame.size.height + [[UIApplication sharedApplication] statusBarFrame].size.height);

    self.menu = [[FSDropDownMenu alloc] initWithOrigin:point andHeight:self.view.frame.size.height * 0.7];
    self.menu.delegate = self;
    [self.navigationController.view addSubview:self.menu];
    
    
}

- (void)viewDidAppear:(BOOL)animated{
    if(!loadControl)
    {
        [self addLoadMoreView];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleWillShowKeyboard:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleWillHideKeyboard:)
                                                 name:UIKeyboardWillHideNotification                                         object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.inputToolBarView resignFirstResponder];
    [self setEditing:NO animated:YES];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)addPullLoadControl{
    self.refreshControl = [[UIRefreshControl alloc] init];
    
    [self.refreshControl setTintColor:AdornColor];
    
    NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"下拉显示分类"];
    self.refreshControl.attributedTitle = str;
    self.state = TLRefreshControlStateNone;
    
    
    //[self.refreshControl setAttributedTitle:[NSAttributedString ]];
}

- (void)refreshVideo:(MNTPullToReactControl *)sender{
    [pullContrl beginAction:sender.action];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [pullContrl endAction:sender.action];
        NSLog(@"Action Button %ld Click",(long)sender.action);
    });
}

#pragma mark -- UIRefreshControl Refresh
- (void)refresh:(void(^)())completion{
    [[AVOSManger sharedManger] updateVideoListsFromAVOSLimition:curVideoCount type:[[AVOSManger sharedManger] videoType] updateCompletion:^(NSArray *v_urls, NSArray *v_names, NSArray *pub_user, NSArray *v_ctimes, NSArray *v_descs, NSArray *likes, NSArray *indexs,NSArray* v_ids,NSArray *v_cate,NSArray *video_cmt_count,NSUInteger videoCount) {
        
        videoUrls = v_urls;
        videoNames = v_names;
        videoCTimes = v_ctimes;
        videoDescs = v_descs;
        videoId = v_ids;
        videoCate = v_cate;
        videoCmtCount = video_cmt_count;
        
        curVideoCount = videoCount;
        
        completion();
    }];
}

- (void)loadMoreVideoWithVideoType:(AVOSVideoType)videoType{
    curVideoCount +=5;
    [[AVOSManger sharedManger] updateVideoListsFromAVOSLimition:curVideoCount type:videoType updateCompletion:^(NSArray *v_urls, NSArray *v_names, NSArray *pub_user, NSArray *v_ctimes, NSArray *v_descs, NSArray *likes, NSArray *indexs,NSArray* v_ids,NSArray *v_cate,NSArray *video_cmt_count,NSUInteger videoCount) {
        
        videoUrls = v_urls;
        videoNames = v_names;
        videoCTimes = v_ctimes;
        videoDescs = v_descs;
        videoId = v_ids;
        videoCate = v_cate;
        videoCmtCount = video_cmt_count;
        
        curVideoCount = videoCount;
        [self.tableView reloadData];
        dispatch_async(dispatch_get_main_queue(), ^{
            [loadControl stop];
        });
    }];
}

- (void)loadMoreVideo{
    [self loadMoreVideoWithVideoType:[[AVOSManger sharedManger] videoType]];
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return videoUrls.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *identifier = @"VideoCell";
    
    TLVideoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    self.currentVideoCell = cell;
    
    if (!cell) {
         cell = [[TLVideoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    cell.delegate = self;
    
    cell.videoDescriptionLabel.text = [videoDescs objectAtIndex:indexPath.row];
    
    [TXYVideoThumbFetcher fetchImageFromURL:[videoUrls objectAtIndex:indexPath.row] completionBlock:^(UIImage *image) {
        dispatch_async(dispatch_get_main_queue(), ^{
        if([image isKindOfClass:[UIImage class]] && image)
        cell.videoPreviewThumb.image = image;    
        });
    }];

    if(((cell.videoPlayer.playerStatus == TLPlayerStatusPlaying) || (cell.videoPlayer.playerStatus == TLPlayerStatusPaused)) && ![[TLCommentManger sharedManger] isOn])
    {
        //[cell resetPlayer];
    }
    
   cell.videoFenlei.text = [videoCate objectAtIndex:indexPath.row];
   cell.cmtLabel.text = [[videoCmtCount objectAtIndex:indexPath.row] stringValue];
    NSLog(@"%@",cell.videoFenlei);
    [TLCategoryManger imageForCategory:cell.videoFenlei.text completion:^(UIImage *cachedImage) {
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.videoColumnImageView.image = cachedImage;
        });
    }];
    
    [cell setVideoAssestURL:[NSURL URLWithString:[videoUrls objectAtIndex:indexPath.row]]];
    
    [cell setVideoID:[videoId objectAtIndex:indexPath.row]];
    
    NSLog(@"%f",cell.frame.origin.y);
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 400.f;
}

- (CGFloat)tableView:(nonnull UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    NSLog(@"Comment Pre Height %lf",self.currentVideoCell.commentThumbTable.frame.size.height);
    
    CGSize fitSize = [self.currentVideoCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    
    CGFloat tWidth = self.currentVideoCell.commentThumbTable.frame.size.width;
    
    
    CGSize tSize = [self.currentVideoCell.commentThumbTable sizeThatFits:TFIL_MAX(tWidth)];
    
    CGFloat fitHeight =fitSize.height+ tSize.height;// - self.currentVideoCell.commentThumbTable.frame.size.height;
    
    NSLog(@"Comment Pre Height %lf",self.currentVideoCell.commentThumbTable.frame.size.height);
    //Adapt For iOS8&7
    
    return fitHeight + 1;
}

/*
#pragma mark - ModelViewController delegate

- (void)modalViewControllerDidClickedDismissButton:(ModalViewController *)viewController{
    [self dismissViewControllerAnimated:YES completion:^{
        self.transitionCell.hidden = NO;
    }];
}

#pragma mark - transition
- (id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    self.transition.present = YES;
    return self.transition;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    self.transition.present = NO;
    return self.transition;
}
*/

#pragma mark - Message InputView Step
- (void)setupInputView{
    UIView *container = [TLCommentManger sharedContainer];
    
    CGSize size = container.frame.size;
    
    CGRect inputFrame = CGRectMake(0.0f, size.height - INPUT_HEIGHT, size.width, INPUT_HEIGHT);
    
    self.inputToolBarView = [[JSMessageInputView alloc] initWithFrame:inputFrame delegate:self];
    
    self.inputToolBarView.backgroundColor = TintColor;
    
    self.inputToolBarView.textView.dismissivePanGestureRecognizer = self.tableView.panGestureRecognizer;
    
    self.inputToolBarView.textView.keyboardDelegate = self;
    
    UIButton *sendButton = [self sendButton];
    sendButton.frame = CGRectMake(self.inputToolBarView.frame.size.width - 55.0f, 8.0f, 36.4f, InputBoxHeight);
    [sendButton addTarget:self
                   action:@selector(sendPressed:)
         forControlEvents:UIControlEventTouchUpInside];
    [sendButton setBackgroundImage:[UIImage imageNamed:@"SendCmt"] forState:UIControlStateNormal];
    [self.inputToolBarView setSendButton:sendButton];
    
    [[TLCommentManger sharedContainer] addSubview:self.inputToolBarView];
}

- (void)sendPressed:(id)sender{
    BOOL islogin = [[AVUser currentUser] isAuthenticated];
    
   __block NSString *sessionToken = [[AVUser currentUser] sessionToken];
    __block NSString *userId = [[AVUser currentUser] username];
    
    if(!islogin)
    {
        [TLLoginViewController showLoginView:self.navigationController completion:^(BOOL isLogin) {
            if(isLogin)
            {
                sessionToken = [[AVUser currentUser] sessionToken];
                   [TLAlertHelper showErrorHUDWithText:@"请先登录"];
//                [[AVOSManger sharedManger] sendComment:self.inputToolBarView.textView.text  videoId:self.currentVideoCell.videoPlayer.v_id userSession:sessionToken completion:^(BOOL succ,NSString *resp) {
//                    [TLAlertHelper dismissHUD];
//                }];
            }
        }];
    }
    else{
    [TLAlertHelper showHUDWithText:@"发送中..."];
        
        [[AVOSManger sharedManger] sendComment:self.inputToolBarView.textView.text  videoId:currentObjectId userId:userId userSession:sessionToken completion:^(BOOL succ,NSString *resp) {
       // dispatch_async(dispatch_get_main_queue(), ^{
            //[TLAlertHelper dismissHUD];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if(succ)
            {
                [TLAlertHelper showSuccessHUDWithText:@"发送成功"];
                [self.inputToolBarView.textView setText:@""];
                [[TLCommentManger sharedManger] reloadData];
            }
            else
                [TLAlertHelper showErrorHUDWithText:@"发送失败"];
        });
       // });
    }];
}
    
    [self.inputToolBarView.textView resignFirstResponder];
}

- (UIButton *)sendButton
{
    return [UIButton defaultSendButton];
}

#pragma mark - VideoEventDelegate
#pragma mark - Comment Event
- (void)videoWillShowComment:(NSString *)v_id cell:(TLVideoCell *)cell{
//    float scaleFactor =  cell.frame.size.height > [TLDeviceManger deviceScreenSize].height ? 1-[cell caculateMainHeight]/[TLDeviceManger deviceScreenSize].height:(1 - cell.frame.size.height/[TLDeviceManger deviceScreenSize].height);
    //show or hiden
    self.isShowCmt = !self.isShowCmt;
    [cell toggleCommentMode:self.isShowCmt];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self setupInputView];
    });
    currentObjectId = v_id;
    //Scale Video Cell
    [TLCommentManger scaleVideoView:cell];
    
    CGPoint transPoint = [cell.separationLine convertPoint:CGPointZero toView:self.view];
    float scaleFactor = [TLDeviceManger deviceScreenSize].width/cell.cellBackgroundView.frame.size.width;
    //Toggle Comment
    [TLCommentManger toggleCommentByVideoId:cell.videoPlayer.v_id heightScale:[TLDeviceManger scaleFactor:scaleFactor andYPos:(transPoint.y+3)] target:self.tableView completion:^(BOOL cpl) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[TLCommentManger sharedContainer] bringSubviewToFront:self.inputToolBarView];
        });
    }];
}

- (void)videoValueChanged:(TLVideoPlayer *)player value:(float)value{
    
}

#pragma mark  Video Play Event
- (void)videoPlay:(TLVideoPlayer *)player{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"VideoWillPlay" object:nil];
    [player play];
}

- (void)videoPaused:(TLVideoPlayer *)player{
    [player pause];
}

- (void)videoFastReward:(TLVideoPlayer *)player{
    
}

- (void)videoFastForward:(TLVideoPlayer *)player{
    
}


#pragma mark -- FSDropDownMenuDelegate
- (void)dropViewDidChanged:(BOOL)isOn{
    self.tableView.scrollEnabled=!isOn;
}

- (void)menu:(FSDropDownMenu *)menu collectionView:(UICollectionView *)collectionView didSelectIndex:(NSUInteger)index title:(NSString *)title{
    NSLog(@"Category is select:%ld title:%@",index,title);
    AVOSVideoType videoType = [[AVOSManger sharedManger] categoryStringToEnum:title];
    NSIndexPath *indexPath = [NSIndexPath indexPathForVideoType:videoType];
    [self.menu setSelectedIndexPath:indexPath];
    [[AVOSManger sharedManger] syncVideoType:title];
    [self refresh:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            self.state = TLRefreshControlStateCategory;
            [self.refreshControl endRefreshing];
            [self.tableView reloadData];
        });
        
    }];
}

#pragma mark  Load More Event
- (void)addLoadMoreView{
    NSLog(@"tableView %@",self.tableView);
    //添加上拉加载的indicator
    loadControl = [[TLLoadControl alloc] initWithScrollView:((UIScrollView *)self.tableView)];
    
    [loadControl statusCallBack:^(TLControlState controlState) {
        if(controlState == TLControlStateBegin)
        {
            //delay can reduce the server pressure
            int delay = arc4random() % 1+1.2;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self loadMoreVideo];
            });
        }
    }];
}

- (void)scrollViewDidEndDragging:(nonnull UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if(isCategorySwOn)
    {
    if(scrollView.contentOffset.y < -70 && scrollView.contentOffset.y > -150)
    {
        [self performRefreshAction];
    }
    else if (scrollView.contentOffset.y < -150)
    {
        [self performRefreshAction];
    }
    }
}

- (void)scrollViewDidScroll:(nonnull UIScrollView *)scrollView{
    if(isCategorySwOn){
    if(scrollView.contentOffset.y < -70 && scrollView.contentOffset.y > -150)
    {
        [self refreshControlStateChanged:TLRefreshControlStateCategory];
    }
    else if (scrollView.contentOffset.y < -150)
    {
        [self refreshControlStateChanged:TLRefreshControlStateRefresh];
    }
    else{
        [self refreshControlStateChanged:TLRefreshControlStateNone];
    }}
    
    [loadControl scrollViewDidScroll:scrollView];
}

- (void)performRefreshAction
{
    if(self.state==TLRefreshControlStateCategory)
    {
            [self.menu menuTapped:^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.refreshControl endRefreshing];
                });
            }];
    }
    else if(self.state == TLRefreshControlStateRefresh)
    {
        [self refresh:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                self.state = TLRefreshControlStateCategory;
                [self.refreshControl endRefreshing];
                [self.tableView reloadData];
            });
            
        }];
    }
}

- (void)refreshControlStateChanged:(TLRefreshControlState)state
{
    NSString *str_  = (state == TLRefreshControlStateCategory)? @"松开显示分类":@"松开后刷新";
    
    if(state == TLRefreshControlStateNone)
        str_ = @"下拉显示分类";
    
    if(self.state != state)
    {
    NSAttributedString *str = [[NSAttributedString alloc] initWithString:str_];
        if(!self.refreshControl.isRefreshing)
            self.refreshControl.attributedTitle = str;
    self.state = state;
    }
}


#pragma mark - Login
- (IBAction)login:(id)sender {
    
}

- (void)prepareForSegue:(nonnull UIStoryboardSegue *)segue sender:(nullable id)sender{
    
}

#pragma mark - View Update
- (void)updateViewByVideoURL:(NSArray *)v_urls{
    videoUrls = v_urls;
    
    curVideoCount = [v_urls count];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Keyboard notifications
- (void)handleWillShowKeyboard:(NSNotification *)notification
{
    [self keyboardWillShowHide:notification];
}

- (void)handleWillHideKeyboard:(NSNotification *)notification
{
    [self keyboardWillShowHide:notification];
}

- (void)keyboardWillShowHide:(NSNotification *)notification
{
    CGRect keyboardRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    UIViewAnimationCurve curve = [[notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration
                          delay:0.0f
                        options:[UIView animationOptionsForCurve:curve]
                     animations:^{
                         CGFloat keyboardY = [[TLCommentManger sharedContainer] convertRect:keyboardRect fromView:nil].origin.y;
                         
                         CGRect inputViewFrame = self.inputToolBarView.frame;
                         CGFloat inputViewFrameY = keyboardY - inputViewFrame.size.height;
                         
                         // for ipad modal form presentations
                         CGFloat messageViewFrameBottom = [TLCommentManger sharedContainer].frame.size.height - INPUT_HEIGHT;
                         if(inputViewFrameY > messageViewFrameBottom)
                             inputViewFrameY = messageViewFrameBottom;
                         
                         self.inputToolBarView.frame = CGRectMake(inputViewFrame.origin.x,
                                                                  inputViewFrameY,
                                                                  inputViewFrame.size.width,
                                                                  inputViewFrame.size.height);
                         
                         UIEdgeInsets insets = UIEdgeInsetsMake(0.0f,
                                                                0.0f,
                                                                self.view.frame.size.height - self.inputToolBarView.frame.origin.y - INPUT_HEIGHT,
                                                                0.0f);
                         
                         self.tableView.contentInset = insets;
                         self.tableView.scrollIndicatorInsets = insets;
                     }
                     completion:^(BOOL finished) {
                     }];
}

#pragma mark - Dismissive text view delegate
- (void)keyboardDidScrollToPoint:(CGPoint)pt
{
    CGRect inputViewFrame = self.inputToolBarView.frame;
    CGPoint keyboardOrigin = [self.view convertPoint:pt fromView:nil];
    inputViewFrame.origin.y = keyboardOrigin.y - inputViewFrame.size.height;
    self.inputToolBarView.frame = inputViewFrame;
}

- (void)keyboardWillBeDismissed
{
    CGRect inputViewFrame = self.inputToolBarView.frame;
    inputViewFrame.origin.y = self.view.bounds.size.height - inputViewFrame.size.height;
    self.inputToolBarView.frame = inputViewFrame;
}

- (void)keyboardWillSnapBackToPoint:(CGPoint)pt
{
    CGRect inputViewFrame = self.inputToolBarView.frame;
    CGPoint keyboardOrigin = [self.view convertPoint:pt fromView:nil];
    inputViewFrame.origin.y = keyboardOrigin.y - inputViewFrame.size.height;
    self.inputToolBarView.frame = inputViewFrame;
}

#pragma mark -- 投稿
- (IBAction)tougaoAction:(id)sender {
    
    [UIView animateWithDuration:0.2 animations:^{
        
    } completion:^(BOOL finished) {
        [self.menu menuTapped:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.menu setSelectedIndexPath:[NSIndexPath indexPathForVideoType:[[AVOSManger sharedManger] videoType]]];
            });
        }];
    }];
}

@end
